<?php

	$username = $_POST["username"];
	$password = $_POST["password"];
	$firstname = $_POST['firstname'];
	$surname = $_POST['surname'];
	$age = $_POST['age'];
	$phone = $_POST['phone'];
	$address = $_POST['address'];
	$crossStreet = $_POST['crossStreet'];
	$email = $_POST["email"];
	$dob = $_POST['dob'];
	if($username != "" && $password != "" && $firstname != "" && $surname != "" && $age != "" && $phone != "" && $address != "" && $crossStreet != "" && $email != "" && $dob != "")
		connect_database();
	else
		echo "<p>Missing Input</p>";

	function connect_database(){
		$mysqli = new mysqli('localhost', 'root', '', 'gluphien');
		if ($mysqli->connect_errno)
			echo "<p>Connection Failed.</p>";
		else
		{
			//echo "this is good";
		}
		$taken = false;
		$SQLstring = "SELECT userID, username FROM `gluphien`.`users`";
		if($result = $mysqli->query($SQLstring)){
			while(($Row = $result->fetch_row())) {
				if($GLOBALS["username"] == $Row[1])
				{
					echo "<p>Username Taken</p>";
					$taken = true;
				}
			}
		}
		if(!$taken){
			$SQLstring = "INSERT INTO `gluphien`.`users` (`userID`, `username`, `password`, `role`) 
			VALUES (NULL, '" . $GLOBALS["username"] . "', '" . $GLOBALS["password"] . "', 'user')";
			mysqli_check($mysqli, $SQLstring);
			//
			//Test
			//
			/*$SQLstring = "INSERT INTO  `gluphien`.`users` (`userID` ,`username` ,`password`)
				VALUES (NULL ,  'testName',  'password')";
			echo "<p> example " . $SQLstring . "</p>";
			if (mysqli_query($mysqli, $SQLstring) === TRUE) {
				echo "<p> success users";
			}
			else
			{
				echo $mysqli->error;
			}*/
			$SQLstring = "SELECT userID, username FROM `gluphien`.`users`";
			if($result = $mysqli->query($SQLstring)){
				while(($Row = $result->fetch_row())) {
					if($GLOBALS["username"] == $Row[1])
					{
						$userID = $Row[0];
					}
				}
			}
			//
			// Old crappy code
			//
			/*$result = $mysqli->query($SQLstring);
			while($obj = $result->fetch_object());
				echo $obj->userID;*/
			//echo $mysqli->query($SQLstring)->fetch_object()->userID;

			$SQLstring = "INSERT INTO `gluphien`.`userdetails` (`userID`, `firstname`, `surname`, `age`, `phone`, `address`, `crossStreet`, `email`, `dateofbirth`) 
				VALUES ('" . $userID . "', '" . $GLOBALS["firstname"] . "', '" . $GLOBALS["surname"] . "', '" . $GLOBALS["age"] . "', '" . $GLOBALS["phone"] . "', '" . $GLOBALS["address"] . "', '" . $GLOBALS["crossStreet"] . "', '" . $GLOBALS["email"] . "', '" . $GLOBALS["dob"] . "')";
			mysqli_check($mysqli, $SQLstring);
			//returns userID back to registration.html
			echo $userID;
		}
		$mysqli->close();
	}

	function mysqli_check($mysqli, $SQLstring){
		if (mysqli_query($mysqli, $SQLstring) === TRUE) {
			//echo "<p> success users";
		}
		else
		{
			echo $mysqli->error;
		}
	}
?>